import React, { useReducer, useState } from 'react';

/**
 * useReducer Hook示例组件
 * 
 * 这个组件展示了React useReducer Hook的多种使用场景：
 * 1. 基本计数器
 * 2. 处理复杂状态对象
 * 3. 多个reducer的使用
 * 4. 使用初始化函数
 * 5. 与useState的比较
 */

// 示例1: 基本计数器reducer
function counterReducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    case 'RESET':
      return 0;
    case 'ADD':
      return state + action.payload;
    default:
      return state;
  }
}

// 示例2: 复杂状态对象的reducer
function todoReducer(state, action) {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        ...state,
        todos: [
          ...state.todos,
          {
            id: Date.now(),
            text: action.payload,
            completed: false
          }
        ]
      };
    case 'TOGGLE_TODO':
      return {
        ...state,
        todos: state.todos.map(todo =>
          todo.id === action.payload
            ? { ...todo, completed: !todo.completed }
            : todo
        )
      };
    case 'DELETE_TODO':
      return {
        ...state,
        todos: state.todos.filter(todo => todo.id !== action.payload)
      };
    case 'CLEAR_COMPLETED':
      return {
        ...state,
        todos: state.todos.filter(todo => !todo.completed)
      };
    default:
      return state;
  }
}

// 示例3: 表单状态的reducer
function formReducer(state, action) {
  switch (action.type) {
    case 'UPDATE_FIELD':
      return {
        ...state,
        [action.field]: action.payload
      };
    case 'RESET_FORM':
      return action.payload || initialFormState;
    case 'SET_ERROR':
      return {
        ...state,
        errors: {
          ...state.errors,
          [action.field]: action.payload
        }
      };
    case 'CLEAR_ERROR':
      const newErrors = { ...state.errors };
      delete newErrors[action.field];
      return {
        ...state,
        errors: newErrors
      };
    default:
      return state;
  }
}

// 初始状态
const initialTodoState = {
  todos: []
};

const initialFormState = {
  username: '',
  email: '',
  password: '',
  errors: {}
};

// 示例4: 使用初始化函数的reducer
function createInitialState(userCount) {
  return {
    users: Array.from({ length: userCount }, (_, i) => ({
      id: i,
      name: `用户${i + 1}`,
      active: true
    })),
    selectedUserId: null
  };
}

function userReducer(state, action) {
  switch (action.type) {
    case 'SELECT_USER':
      return {
        ...state,
        selectedUserId: action.payload
      };
    case 'TOGGLE_ACTIVE':
      return {
        ...state,
        users: state.users.map(user =>
          user.id === action.payload
            ? { ...user, active: !user.active }
            : user
        )
      };
    case 'ADD_USER':
      return {
        ...state,
        users: [
          ...state.users,
          {
            id: state.users.length,
            name: action.payload,
            active: true
          }
        ]
      };
    default:
      return state;
  }
}

function UseReducerExample() {
  // 示例1: 基本计数器
  const [count, dispatchCount] = useReducer(counterReducer, 0);
  
  // 示例2: 复杂状态对象
  const [todoState, dispatchTodo] = useReducer(todoReducer, initialTodoState);
  const [newTodo, setNewTodo] = useState('');
  
  // 示例3: 表单状态
  const [formState, dispatchForm] = useReducer(formReducer, initialFormState);
  
  // 示例4: 使用初始化函数
  const [userState, dispatchUser] = useReducer(
    userReducer,
    3, // 初始用户数量
    createInitialState // 初始化函数
  );
  
  // 示例5: 与useState的比较
  const [countWithState, setCountWithState] = useState(0);
  
  // 处理添加待办事项
  const handleAddTodo = (e) => {
    e.preventDefault();
    if (newTodo.trim()) {
      dispatchTodo({ type: 'ADD_TODO', payload: newTodo });
      setNewTodo('');
    }
  };
  
  // 处理表单字段更新
  const handleFormChange = (e) => {
    const { name, value } = e.target;
    dispatchForm({
      type: 'UPDATE_FIELD',
      field: name,
      payload: value
    });
    
    // 简单的表单验证
    if (name === 'email' && !value.includes('@')) {
      dispatchForm({
        type: 'SET_ERROR',
        field: 'email',
        payload: '请输入有效的电子邮件地址'
      });
    } else if (name === 'email') {
      dispatchForm({
        type: 'CLEAR_ERROR',
        field: 'email'
      });
    }
    
    if (name === 'password' && value.length < 6) {
      dispatchForm({
        type: 'SET_ERROR',
        field: 'password',
        payload: '密码必须至少包含6个字符'
      });
    } else if (name === 'password') {
      dispatchForm({
        type: 'CLEAR_ERROR',
        field: 'password'
      });
    }
  };
  
  // 处理表单提交
  const handleFormSubmit = (e) => {
    e.preventDefault();
    alert(`表单提交: ${JSON.stringify(formState, null, 2)}`);
  };
  
  // 添加新用户
  const [newUserName, setNewUserName] = useState('');
  const handleAddUser = () => {
    if (newUserName.trim()) {
      dispatchUser({ type: 'ADD_USER', payload: newUserName });
      setNewUserName('');
    }
  };
  
  return (
    <div className="hook-example">
      <h2>useReducer Hook 示例</h2>
      
      <section>
        <h3>1. 基本计数器</h3>
        <div className="counter-example">
          <p>计数: {count}</p>
          <div className="button-group">
            <button onClick={() => dispatchCount({ type: 'INCREMENT' })}>
              增加
            </button>
            <button onClick={() => dispatchCount({ type: 'DECREMENT' })}>
              减少
            </button>
            <button onClick={() => dispatchCount({ type: 'RESET' })}>
              重置
            </button>
            <button onClick={() => dispatchCount({ type: 'ADD', payload: 5 })}>
              增加5
            </button>
          </div>
        </div>
      </section>
      
      <section>
        <h3>2. 复杂状态对象 (待办事项列表)</h3>
        <div className="todo-example">
          <form onSubmit={handleAddTodo}>
            <input
              type="text"
              value={newTodo}
              onChange={(e) => setNewTodo(e.target.value)}
              placeholder="添加新待办事项"
            />
            <button type="submit">添加</button>
          </form>
          
          <ul className="todo-list">
            {todoState.todos.map(todo => (
              <li key={todo.id} className={todo.completed ? 'completed' : ''}>
                <span onClick={() => dispatchTodo({ 
                  type: 'TOGGLE_TODO', 
                  payload: todo.id 
                })}>
                  {todo.text}
                </span>
                <button onClick={() => dispatchTodo({ 
                  type: 'DELETE_TODO', 
                  payload: todo.id 
                })}>
                  删除
                </button>
              </li>
            ))}
          </ul>
          
          {todoState.todos.length > 0 && (
            <button onClick={() => dispatchTodo({ type: 'CLEAR_COMPLETED' })}>
              清除已完成
            </button>
          )}
        </div>
      </section>
      
      <section>
        <h3>3. 表单状态管理</h3>
        <div className="form-example">
          <form onSubmit={handleFormSubmit}>
            <div className="form-group">
              <label>用户名:</label>
              <input
                type="text"
                name="username"
                value={formState.username}
                onChange={handleFormChange}
              />
            </div>
            
            <div className="form-group">
              <label>电子邮件:</label>
              <input
                type="email"
                name="email"
                value={formState.email}
                onChange={handleFormChange}
              />
              {formState.errors.email && (
                <div className="error">{formState.errors.email}</div>
              )}
            </div>
            
            <div className="form-group">
              <label>密码:</label>
              <input
                type="password"
                name="password"
                value={formState.password}
                onChange={handleFormChange}
              />
              {formState.errors.password && (
                <div className="error">{formState.errors.password}</div>
              )}
            </div>
            
            <div className="button-group">
              <button type="submit">提交</button>
              <button 
                type="button" 
                onClick={() => dispatchForm({ type: 'RESET_FORM' })}
              >
                重置
              </button>
            </div>
          </form>
          
          <div className="form-preview">
            <h4>表单状态:</h4>
            <pre>
              {JSON.stringify({
                username: formState.username,
                email: formState.email,
                password: formState.password ? '******' : '',
                errors: formState.errors
              }, null, 2)}
            </pre>
          </div>
        </div>
      </section>
      
      <section>
        <h3>4. 使用初始化函数</h3>
        <div className="user-example">
          <div className="user-list">
            <h4>用户列表:</h4>
            <ul>
              {userState.users.map(user => (
                <li 
                  key={user.id} 
                  className={user.id === userState.selectedUserId ? 'selected' : ''}
                  onClick={() => dispatchUser({ 
                    type: 'SELECT_USER', 
                    payload: user.id 
                  })}
                >
                  {user.name} 
                  <span className={user.active ? 'active' : 'inactive'}>
                    ({user.active ? '活跃' : '非活跃'})
                  </span>
                  <button onClick={(e) => {
                    e.stopPropagation();
                    dispatchUser({ type: 'TOGGLE_ACTIVE', payload: user.id });
                  }}>
                    切换状态
                  </button>
                </li>
              ))}
            </ul>
            
            <div className="add-user">
              <input
                type="text"
                value={newUserName}
                onChange={(e) => setNewUserName(e.target.value)}
                placeholder="新用户名"
              />
              <button onClick={handleAddUser}>添加用户</button>
            </div>
          </div>
          
          <div className="user-details">
            <h4>选中的用户:</h4>
            {userState.selectedUserId !== null ? (
              <pre>
                {JSON.stringify(
                  userState.users.find(u => u.id === userState.selectedUserId),
                  null,
                  2
                )}
              </pre>
            ) : (
              <p>未选择用户</p>
            )}
          </div>
        </div>
      </section>
      
      <section>
        <h3>5. useReducer vs useState</h3>
        <div className="comparison-example">
          <div className="reducer-example">
            <h4>使用 useReducer:</h4>
            <p>计数: {count}</p>
            <button onClick={() => dispatchCount({ type: 'INCREMENT' })}>
              增加
            </button>
          </div>
          
          <div className="state-example">
            <h4>使用 useState:</h4>
            <p>计数: {countWithState}</p>
            <button onClick={() => setCountWithState(countWithState + 1)}>
              增加
            </button>
          </div>
          
          <div className="comparison-notes">
            <h4>比较:</h4>
            <ul>
              <li>
                <strong>useState</strong>: 适用于简单状态逻辑
              </li>
              <li>
                <strong>useReducer</strong>: 适用于复杂状态逻辑，特别是当状态更新依赖于之前的状态或需要处理多个子值时
              </li>
              <li>
                useReducer让状态更新逻辑与UI组件分离，更容易测试和维护
              </li>
              <li>
                useReducer提供了更可预测的状态转换，类似于Redux的模式
              </li>
            </ul>
          </div>
        </div>
      </section>
      
      <div className="explanation">
        <h3>useReducer Hook 说明:</h3>
        <ul>
          <li><code>const [state, dispatch] = useReducer(reducer, initialState, init)</code></li>
          <li>reducer: <code>(state, action) => newState</code> - 根据当前状态和动作返回新状态的函数</li>
          <li>initialState: 初始状态值</li>
          <li>init: (可选) 初始化函数，用于惰性创建初始状态</li>
          <li>适用场景:
            <ul>
              <li>复杂的状态逻辑，涉及多个子值</li>
              <li>状态转换依赖于之前的状态</li>
              <li>需要在深层组件树中更新状态（结合Context使用）</li>
              <li>测试和调试状态变化</li>
            </ul>
          </li>
          <li>与Redux相比，useReducer是React内置的，更轻量级，适用于组件级状态管理</li>
        </ul>
      </div>
    </div>
  );
}

export default UseReducerExample;